/*
 * Copyright 2004 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.extremecomponents.table.tag;

import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TryCatchFinally;

import org.apache.commons.lang.StringUtils;
import org.extremecomponents.table.bean.Table;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.filter.BufferResponseWrapper;
import org.extremecomponents.table.interceptor.TableInterceptor;
import org.extremecomponents.table.tag.TagUtils;
import org.extremecomponents.util.ExceptionUtils;
import org.extremecomponents.util.XmlUtils;

/**
 * @jsp.tag name="table" display-name="TableTag" body-content="JSP"
 *          description="The container which holds all the main table
 *          information. Will also hold global information if needed. The table
 *          tag is copied into the Table and encapsulated in the Model."
 * 
 * @author Jeff Johnston
 */
public class TableItemsTag extends org.extremecomponents.table.tag.TableTag implements TryCatchFinally, TableInterceptor {

	public static final String AJAX_PARAMETER = "extremecomponents_ajax";
	public static final String AJAX_NODE_TAG = "extremecomponents";
	public static final String AJAX_SCRIPT_METHOD = "ExtremeComponents.submitTable";
	
	private Object items;
	
	//--------- add proper --------
	private String ajax;
	private String template;
	
	private String tableId;
	private String divId;
	private String parameterId;

    public Object getItems() {
		return items;
	}

	public void setItems(Object items) {
		this.items = items;
	}	

	public String getTemplate() {
		return template;
	}

	public void setTemplate(String template) {
		this.template = template;
	}

	public String getAjax() {
		return ajax;
	}

	public void setAjax(String ajax) {
		this.ajax = ajax;
	}

	public void addTableAttributes(TableModel model, Table table) {
		//------- change by sshwsfc for items is Object[] in jsp -----------
		if(this.items instanceof Collection){
        	table.setItems(this.items);
        }else if(this.items instanceof Map){
        	table.setItems(this.items);
        }else{
            table.setItems(TagUtils.evaluateExpressionAsObject("items", this.items, this, pageContext));
        }
		//------ if ajax init OnInvokeAction ---------------
		if(!StringUtils.isNotBlank(table.getOnInvokeAction()) && ajax.equalsIgnoreCase(Boolean.TRUE.toString())){
			//FIX I must init table default, I want get tableId, but it final;
			table.defaults();
			
			this.tableId = table.getTableId();
			this.divId = AJAX_NODE_TAG + "_" + tableId + "Div";
			
			table.setOnInvokeAction(AJAX_SCRIPT_METHOD + "('"+ tableId +"','"+ divId +"');");
		}
	}

    public int doEndTag() throws JspException {
        try {
			this.parameterId = AJAX_PARAMETER + "_" + model.getTableHandler().getTable().getTableId();
        	String ajaxParam = ((HttpServletRequest)(pageContext.getRequest())).getHeader(parameterId);
        	if(ajax.equalsIgnoreCase(Boolean.TRUE.toString()) && 
        			StringUtils.isNotEmpty(ajaxParam) &&
        			ajaxParam.equalsIgnoreCase(Boolean.TRUE.toString())){
        		//ajax and req.xmlHttp
        		HttpServletResponse response;
        		if(BufferResponseWrapper.class.isAssignableFrom(pageContext.getResponse().getClass())){
        			response = ((BufferResponseWrapper)pageContext.getResponse()).getOriginalResponse();
        		}else{
        			response = (HttpServletResponse)pageContext.getResponse();
        		}
        		
        		HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
        		XmlUtils.sendTableData(response, request, model);
        	}else if(ajax.equalsIgnoreCase(Boolean.TRUE.toString()) && StringUtils.isNotBlank(divId)){
        		//ajax but frist get data
        		pageContext.getOut().println("<div id=\""+ divId + "\">");
        		pageContext.getOut().println(model.getViewData());
        		pageContext.getOut().println("</div>");
        	}else{
        		pageContext.getOut().println(model.getViewData());        		
        	}
        } catch (Exception e) {
            throw new JspException("TableTag.doEndTag() Problem: " + ExceptionUtils.formatStackTrace(e));
        }

        return EVAL_PAGE;
    }
}